<template>
  <div class="room-list-container">
    <!-- 添加/编辑机房对话框 -->
    <room-form
      v-model:visible="dialogVisible"
      :room-data="currentRoom"
      @success="handleFormSuccess"
    />

    <div class="content-wrapper">
      <page-header
        title="机房管理"
        description="管理数据中心的机房资源，包括机房基本信息、环境监控、设备统计等。可以查看机房的使用情况、环境状态，并进行机房的添加、编辑和删除操作。"
      >
        <el-input v-model="searchQuery" placeholder="搜索机房..." class="search-input" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </page-header>

      <!-- 机房列表 -->
      <el-table v-loading="loading" :data="filteredRooms" style="width: 100%" :height="tableHeight">
        <el-table-column prop="room_id" label="ID" width="80" fixed="left" />
        <el-table-column prop="room_name" label="机房名称" width="160" fixed="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              {{ row.room_name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="位置" min-width="180" show-overflow-tooltip />
        <el-table-column prop="building_name" label="建筑" width="120" show-overflow-tooltip />
        <el-table-column prop="floor_number" label="楼层" width="80" align="center" />
        <el-table-column label="机柜使用" width="180">
          <template #default="{ row }">
            <el-tooltip
              :content="`${row.total_cabinets - row.available_cabinets}/${row.total_cabinets}`"
              placement="top"
            >
              <el-progress
                :percentage="
                  Math.round(
                    ((row.total_cabinets - row.available_cabinets) / row.total_cabinets) * 100,
                  )
                "
                :status="getUsageStatus(row.available_cabinets, row.total_cabinets)"
                :stroke-width="12"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="电力使用" width="180">
          <template #default="{ row }">
            <el-tooltip
              :content="`${row.used_power_capacity}/${row.total_power_capacity}kW`"
              placement="top"
            >
              <el-progress
                :percentage="Math.round((row.used_power_capacity / row.total_power_capacity) * 100)"
                :status="
                  getUsageStatus(
                    row.total_power_capacity - row.used_power_capacity,
                    row.total_power_capacity,
                  )
                "
                :stroke-width="12"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="环境" width="160">
          <template #default="{ row }">
            <div class="environment-info">
              <el-tag size="small">
                <el-icon class="el-icon--left"><Sunny /></el-icon>
                {{ row.temperature }}°C
              </el-tag>
              <el-tag size="small" type="info">
                <el-icon class="el-icon--left"><Umbrella /></el-icon>
                {{ row.humidity }}%
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
                :disabled="row.cabinet_count > 0"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :teleported="false"
          popper-class="pagination-select-dropdown"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <floating-action-button tooltip="添加机房" @click="handleAdd" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Search, Sunny, Umbrella, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { RoomInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import PageHeader from '@/components/common/PageHeader.vue'
import RoomForm from '@/components/asset/RoomForm.vue'
import FloatingActionButton from '@/components/common/FloatingActionButton.vue'

const router = useRouter()
const loading = ref(false)
const rooms = ref<RoomInfo[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref(500)
const dialogVisible = ref(false)
const currentRoom = ref<RoomInfo>()

// 计算表格高度
const updateTableHeight = () => {
  // 获取视口高度
  const vh = window.innerHeight
  // 减去顶部导航栏高度(64px)、页面padding(48px)、工具栏高度(52px)、分页器高度(32px)、边距(24px)
  tableHeight.value = vh - 64 - 48 - 52 - 32 - 24
}

// 监听窗口大小变化
onMounted(() => {
  updateTableHeight()
  window.addEventListener('resize', updateTableHeight)
  fetchRooms()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})

// 过滤后的机房列表
const filteredRooms = computed(() => {
  if (!searchQuery.value) return rooms.value
  const query = searchQuery.value.toLowerCase()
  return rooms.value.filter(
    (room) =>
      room.room_name.toLowerCase().includes(query) ||
      room.location.toLowerCase().includes(query) ||
      room.building_name.toLowerCase().includes(query),
  )
})

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '异常':
      return 'danger'
    case '维护中':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取使用状态
const getUsageStatus = (available: number, total: number) => {
  const usagePercent = ((total - available) / total) * 100
  if (usagePercent >= 90) {
    return 'exception' // 红色
  }
  if (usagePercent >= 75) {
    return 'warning' // 黄色
  }
  return 'success' // 绿色
}

// 获取机房列表
const fetchRooms = async () => {
  loading.value = true
  try {
    const response = await assetService.getRooms({
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    rooms.value = response.items
    total.value = response.total
  } catch (err) {
    console.error('获取机房列表失败:', err)
    ElMessage.error('获取机房列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查看详情
const handleView = (room: RoomInfo) => {
  router.push(`/asset/room/${room.room_id}`)
}

// 处理添加
const handleAdd = () => {
  currentRoom.value = undefined
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: RoomInfo) => {
  currentRoom.value = row
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (room: RoomInfo) => {
  // 如果机房内有机柜，禁止删除
  if (room.cabinet_count > 0) {
    ElMessage.warning('该机房内还有机柜，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除机房 "${room.room_name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    loading.value = true
    await assetService.deleteRoom(room.room_id)
    ElMessage.success('删除成功')
    // 重新加载列表
    await fetchRooms()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除机房失败:', err)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchRooms()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchRooms()
}

// 处理表单提交成功
const handleFormSuccess = () => {
  fetchRooms() // 重新加载机房列表
}
</script>

<style scoped lang="scss">
.room-list-container {
  height: 100%;

  .content-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    padding-bottom: 48px;

    :deep(.el-table) {
      border: none;
      margin-bottom: 0;

      .el-table__body-wrapper {
        overflow-y: auto;
      }

      // 固定列阴影
      .el-table__fixed-right::before,
      .el-table__fixed::before {
        display: none;
      }

      // 表头样式
      .el-table__header {
        th {
          background-color: var(--el-fill-color-darker);
          &.is-leaf {
            border-bottom: 1px solid var(--el-border-color-lighter);
          }
          .cell {
            font-weight: 600;
            color: var(--el-text-color-regular);
            font-size: 14px;
          }
        }
      }

      &::after {
        display: none;
      }

      .el-table__cell {
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      // 优化行样式
      .el-table__row {
        &:hover {
          background-color: var(--el-fill-color-light);
        }

        .el-table__cell {
          border-bottom: 1px solid var(--el-border-color-lighter);
        }
      }

      .el-button--link {
        height: auto;
        padding: 4px 8px;
        font-size: 14px;
        font-weight: normal;
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 32px;
      display: flex;
      justify-content: flex-end;
      padding: 8px 8px 8px 0;
      border-top: 1px solid var(--el-border-color-lighter);
      z-index: 1;

      :deep(.el-pagination) {
        .el-select .el-input {
          margin: 0;
        }

        .el-select .el-input__wrapper {
          box-shadow: none;
        }
      }
    }
  }
}
/* 新增全局样式（注意需要穿透scoped限制） */
:deep(.pagination-select-dropdown) {
  /* 强制弹窗向上展开 */
  top: auto !important;
  bottom: 100%;
  margin-bottom: 28px; /* 添加与分页器的间距 */

  /* 调整箭头方向 */
  .el-popper__arrow {
    top: 100%;
    bottom: auto;
    transform: translateY(-50%) rotate(180deg);
  }
}

.environment-info {
  display: flex;
  gap: 8px;

  :deep(.el-tag) {
    .el-icon--left {
      margin-right: 2px;
      vertical-align: middle;
    }
  }
}
</style>
